using GameServer.Concurrent;
using Protocol.Dto.Fight;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GameServer.Cache.Fight
{
    /// <summary>
    /// 战斗的缓存层
    /// </summary>
    public class FightCache
    {
        /// <summary>
        /// 用户id 与 房间id 的映射
        /// </summary>
        private Dictionary<int, int> uidRoomIDict = new Dictionary<int, int>();
        /// <summary>
        /// 房间id 与 房间模型 的映射
        /// </summary>
        private Dictionary<int, FightRoom> idRoomDict = new Dictionary<int, FightRoom>();

        /// <summary>
        /// 房间的重用队列
        /// </summary>
        private Queue<FightRoom> roomQueue = new Queue<FightRoom>();

        /// <summary>
        /// 房间的id
        /// </summary>
        private ConcurrentInt id = new ConcurrentInt(-1);

        /// <summary>
        /// 创建房间
        /// </summary>
        public FightRoom Create(List<int> uidList)
        {
            FightRoom room = null;
            if (roomQueue.Count > 0)
            {
                room = roomQueue.Dequeue();
                room.Init(uidList);
            }
            else
            {
                room = new FightRoom(id.Add_Get(), uidList);
            }
            foreach (int uid in uidList)
            {
                uidRoomIDict.Add(uid, room.Id);
            }
            idRoomDict.Add(room.Id, room);
            return room;
        }

        public FightRoom GetRoom(int id)
        {
            if (!idRoomDict.ContainsKey(id))
            {
                throw new Exception("不存在此房间");
            }
            return idRoomDict[id];
        }

        public bool IsFighting(int userId)
        {
            return uidRoomIDict.ContainsKey(userId);
        }

        public FightRoom GetRoomByUid(int userId)
        {
            if (!uidRoomIDict.ContainsKey(userId))
            {
                throw new Exception("当前用户不在房间");
            }
            return GetRoom(uidRoomIDict[userId]);
        }

        /// <summary>
        /// 摧毁房间
        /// </summary>
        public void Destory(FightRoom room)
        {
            idRoomDict.Remove(room.Id);
            foreach (PlayerDto player in room.PlayerList)
            {
                uidRoomIDict.Remove(player.UserId);
            }
            // 初始化房间数据

            room.PlayerList.Clear();
            room.LeaveUIdList.Clear();
            room.TableCardList.Clear();
            room.libraryModel.Init();
            room.Mutiple = 1;
            room.roundModel.Init();

            // 添加等待队列等待重用
            roomQueue.Enqueue(room);
        }
    }
    

}
